package cn.iocoder.yudao.module.ai.service.label;

import cn.iocoder.yudao.framework.exception.BusinessException;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.ai.dal.dataobject.label.LabelDO;
import cn.iocoder.yudao.module.ai.dal.dataobject.label.LabelRelationDO;
import cn.iocoder.yudao.module.ai.dal.mysql.label.LabelMapper;
import cn.iocoder.yudao.module.ai.dal.mysql.label.LabelRelationMapper;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.ai.controller.admin.label.vo.*;
import cn.iocoder.yudao.module.ai.dal.dataobject.label.LabelGroupDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.ai.dal.mysql.label.LabelGroupMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.ai.enums.ErrorCodeConstants.*;

/**
 * 标签组管理 Service 实现类
 *
 * @author 侯俊青
 */
@Service
@Validated
public class LabelGroupServiceImpl implements LabelGroupService {

    @Resource
    private LabelGroupMapper labelGroupMapper;
    @Resource
    private LabelMapper labelMapper;
    @Resource
    private LabelRelationMapper labelRelationMapper;
    @Resource
    private DeptApi deptApi ;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createLabelGroup(LabelGroupSaveReqVO createReqVO) {
        // 插入
        LabelGroupDO labelGroup = BeanUtils.toBean(createReqVO, LabelGroupDO.class);
        labelGroup.setId(null);
        labelGroup.setSuplierId(deptApi.queryFirstDept(SecurityFrameworkUtils.getLoginUserDeptId()));
        labelGroupMapper.insert(labelGroup);

        // 插入 关联信息
        if(CollectionUtils.isNotEmpty(createReqVO.getLabelIds())){
            List<LabelDO> labelDOS = labelMapper.selectBatchIds(createReqVO.getLabelIds());
            if(CollectionUtils.isEmpty(labelDOS)){
                throw exception(LABEL_NOT_EXISTS);
            }
            if(createReqVO.getLabelIds().size() != labelDOS.size()){
                throw new BusinessException("包含标签编号设置错误，请确认标签编号是否存在，或者包含重复编号");
            }
            List<LabelRelationDO> labelRelationDOList = new ArrayList<>();
            createReqVO.getLabelIds().forEach(item -> {
                labelRelationDOList.add(new LabelRelationDO().setGroupId(labelGroup.getId()).setLabelId(item).setSuplierId(deptApi.queryFirstDept(SecurityFrameworkUtils.getLoginUserDeptId())));
            });
            labelRelationMapper.insertBatch(labelRelationDOList);
        }

        // 返回
        return labelGroup.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateLabelGroup(LabelGroupSaveReqVO updateReqVO) {
        // 校验存在
        validateLabelGroupExists(updateReqVO.getId());
        // 更新
        LabelGroupDO updateObj = BeanUtils.toBean(updateReqVO, LabelGroupDO.class);
        labelGroupMapper.updateById(updateObj);
        // 删除旧的关联
        labelGroupMapper.deleteLabelRelationByGroupId(updateReqVO.getId());
        // 插入 关联信息
        if(CollectionUtils.isNotEmpty(updateReqVO.getLabelIds())){
            List<LabelDO> labelDOS = labelMapper.selectBatchIds(updateReqVO.getLabelIds());
            if(CollectionUtils.isEmpty(labelDOS)){
                throw exception(LABEL_NOT_EXISTS);
            }
            if(updateReqVO.getLabelIds().size() != labelDOS.size()){
                throw new BusinessException("包含标签编号设置错误，请确认标签编号是否存在，或者包含重复编号");
            }
            List<LabelRelationDO> labelRelationDOList = new ArrayList<>();
            updateReqVO.getLabelIds().forEach(item -> {
                labelRelationDOList.add(new LabelRelationDO().setGroupId(updateReqVO.getId()).setLabelId(item));
            });
            labelRelationMapper.insertBatch(labelRelationDOList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteLabelGroup(Long id) {
        // 校验存在
        validateLabelGroupExists(id);
        // 先删除关联信息
        labelGroupMapper.deleteLabelRelationByGroupId(id);
        // 删除
        labelGroupMapper.deleteById(id);
    }

    private void validateLabelGroupExists(Long id) {
        if (labelGroupMapper.selectById(id) == null) {
            throw exception(LABEL_GROUP_NOT_EXISTS);
        }
    }

    @Override
    public LabelGroupDO getLabelGroup(Long id) {
        return labelGroupMapper.selectById(id);
    }

    @Override
    public PageResult<LabelGroupDO> getLabelGroupPage(LabelGroupPageReqVO pageReqVO) {
        return labelGroupMapper.selectPage(pageReqVO);
    }

}